require("../utils/extend");

function add_int8(cmd_buf,num){
	if (cmd_buf==null){
		cmd_buf=Buffer.allocUnsafe(1);
		cmd_buf.writeInt8(num,0);
	}
	else{
		var buf=Buffer.allocUnsafe(1);
		buf.writeInt8(num,0);
		cmd_buf=Buffer.concat([cmd_buf,buf]);
	}
	
	return cmd_buf;
}

function get_int8(cmd_buf){
	var num=cmd_buf.readInt8(0);
	return [num,cmd_buf.slice(1)];
}

function add_int16(cmd_buf,num){
	if (cmd_buf==null){
		cmd_buf=Buffer.allocUnsafe(2);
		cmd_buf.writeInt16BE(num,0);
	}
	else{
		var buf=Buffer.allocUnsafe(2);
		buf.writeInt16BE(num,0);
		cmd_buf=Buffer.concat([cmd_buf,buf]);
	}
	
	return cmd_buf;
}

function get_int16(cmd_buf){
	var num=cmd_buf.readInt16BE(0);
	return [num,cmd_buf.slice(2)];
}

function add_int32(cmd_buf,num){
	if (cmd_buf==null){
		cmd_buf=Buffer.allocUnsafe(4);
		cmd_buf.writeInt32BE(num,0);
	}
	else{
		var buf=Buffer.allocUnsafe(4);
		buf.writeInt32BE(num,0);
		cmd_buf=Buffer.concat([cmd_buf,buf]);
	}
	
	return cmd_buf;
}

function get_int32(cmd_buf){
	var num=cmd_buf.readInt32BE(0);
	return [num,cmd_buf.slice(4)];
}

function add_uint32(cmd_buf,num){
	if (cmd_buf==null){
		cmd_buf=Buffer.allocUnsafe(4);
		cmd_buf.writeUInt32BE(num,0);
	}
	else{
		var buf=Buffer.allocUnsafe(4);
		buf.writeUInt32BE(num,0);
		cmd_buf=Buffer.concat([cmd_buf,buf]);
	}
	
	return cmd_buf;
}

function get_uint32(cmd_buf){
	var num=cmd_buf.readUInt32BE(0);
	return [num,cmd_buf.slice(4)];
}

function add_float(cmd_buf,num){
	if (cmd_buf==null){
		cmd_buf=Buffer.allocUnsafe(4);
		cmd_buf.writeFloatBE(num,0);
	}
	else{
		var buf=Buffer.allocUnsafe(4);
		buf.writeFloatBE(num,0);
		cmd_buf=Buffer.concat([cmd_buf,buf]);
	}
	
	return cmd_buf;
}

function get_float(cmd_buf){
	var num=cmd_buf.readFloatBE(0);
	return [num,cmd_buf.slice(4)];
}


function add_str(cmd_buf,str){
	var len=str.utf8_byte_len();
	if (cmd_buf==null){
		cmd_buf=Buffer.allocUnsafe(len);
		cmd_buf.write(str,0);
	}
	else{
		var buf=Buffer.allocUnsafe(len);
		buf.write(str,0);
		cmd_buf=Buffer.concat([cmd_buf,buf]);
	}

	return cmd_buf;
}

function add_str16(cmd_buf,str){
	var len=str.utf8_byte_len();
	if (cmd_buf==null){
		cmd_buf=Buffer.allocUnsafe(len+2);
		cmd_buf.writeInt16BE(len,0);
		cmd_buf.write(str,2);
	}else{
		var buf=Buffer.allocUnsafe(len+2);
		buf.writeInt16BE(len,0);
		buf.write(str,2);
		cmd_buf=Buffer.concat([cmd_buf,buf]);
	}

	return cmd_buf;
}

function get_str(cmd_buf,len){
	var str=cmd_buf.toString("utf8",0,len);
	return [str,cmd_buf.slice(len)];
}

function get_str16(cmd_buf){
	var len=cmd_buf.readInt16BE(0);
	var str=cmd_buf.toString("utf8",2,2+len);
	return [str,cmd_buf.slice(2+len)];
}

var protocol_tool={
	add_int8:add_int8,
	get_int8:get_int8,
	add_int16:add_int16,
	get_int16:get_int16,
	add_int32:add_int32,
	get_int32:get_int32,
	add_uint32:add_uint32,
	get_uint32:get_uint32,
	add_float:add_float,
	get_float:get_float,
	add_str:add_str,
	add_str16:add_str16,
	get_str:get_str,
	get_str16:get_str16,
};

module.exports=protocol_tool;